﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Wicresoft.Common;
using Wicresoft.Framework.Organization;
using JDEduTrain.Framework.Business;
using JDEduTrain.Framework.Entity;


public partial class Page_NewTrainClass : BaseAuthenticationPage
{
    private Guid ClassID
    {
        get
        {
            if (Request["ClassID"] != null)
            {
                return new Guid(Request["ClassID"]);

            }
            return Guid.Empty;
        }
    }

    protected DataTable DTClassOrder
    {
        get
        {
            if (ViewState["DTClassOrder"] != null)
            {
                return (DataTable)ViewState["DTClassOrder"];
            }
            return new DataTable();
        }
        set
        {
            ViewState["DTClassOrder"] = value;
        }
    }

    //临时ClassID
    protected string TempoClassID
    {
        get
        {
            if (ViewState["TempoClassID"] != null)
                return ViewState["TempoClassID"].ToString();
            return string.Empty;
        }
        set
        {
            ViewState["TempoClassID"] = value;
        }
    }



    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = "新建培训班级";


        if (!IsPostBack)
        {
            string path = Server.MapPath(@"~/Library/User/" + CurrentUser.Name);
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);//在指定路径下新建一个文件夹
            }
            tbCurriculum.SetSecurityImageGalleryPath(@"~/Library/User/" + CurrentUser.Name);
            if (ClassID != Guid.Empty)
            {

                TrainClass trainClass = new TrainClass(ClassID);
                if (trainClass.Load())
                {

                    if (!string.IsNullOrEmpty(trainClass.BeginTime.ToString()))
                    {
                        tbBeginTime.Text = Convert.ToDateTime(trainClass.BeginTime).ToShortDateString();
                    }
                    if (!string.IsNullOrEmpty(trainClass.EndTime.ToString()))
                    {
                        tbEndTime.Text = Convert.ToDateTime(trainClass.EndTime).ToShortDateString();
                    }
                    tbClassName.Text = trainClass.ClassName;
                    tbComment.Text = WebCommon.GetStandardStyleStr(trainClass.Comment);
                    tbCourseInfo.Text = trainClass.CourseInfo;
                    tbCourseScore.Text = trainClass.Score.ToString();
                    tbPlace.Text = trainClass.Place;
                    tbLectorInfo.Text = trainClass.LectorInfo;
                    tbCurriculum.Text = trainClass.Curriculum;
                    tbDeptDisplayName.Text = trainClass.ApplyOrgan;
                    tbDeptID.Text = trainClass.ApplyOrganID;
                    tbDeptName.Text = trainClass.ApplyOrgan;
                    tbApplyEndTime.Text = trainClass.ApplyEndTime.ToShortDateString();
                    tbHostUnit.Text = trainClass.HostUnit;
                    tbTrainDayCount.Text = trainClass.TrainDayCount.ToString();
                    if (!string.IsNullOrEmpty(trainClass.TrainLevel))
                    {
                        ddlTrainLevel.SelectedValue = trainClass.TrainLevel;
                    }
                }
                this.Title = "编辑培训班级";
            }
            TempoClassID = Guid.NewGuid().ToString();
            BindOrder();
            tbDeptDisplayName.Attributes["readonly"] = "readonly";


        }
    }

    protected void BindOrder()
    {
        DataTable dtOrder;
        if (ClassID != Guid.Empty)
        {
            dtOrder = BLTrain.GetOrderByClassID(ClassID);
        }
        else
        {
            string specialClassID = GetSpecialClassID(TempoClassID);
            dtOrder = BLTrain.GetOrderByClassID(new Guid(specialClassID));
        }
        rptOrderInfo.DataSource = dtOrder;
        rptOrderInfo.DataBind();

    }

    protected void lbtnSave_Click(object sender, EventArgs e)
    {
        //暂时去除班次概念
        //DataTable dtOrderOut;
        //if (ClassID != Guid.Empty)
        //{
        //    dtOrderOut = BLTrain.GetOrderByClassID(ClassID);
        //}
        //else
        //{
        //    string specialClassID = GetSpecialClassID(TempoClassID);
        //    dtOrderOut = BLTrain.GetOrderByClassID(new Guid(specialClassID));
        //}
        //string script;
        //if (dtOrderOut.Rows.Count > 0)
        //{
        TrainClass trainClass = new TrainClass(ClassID);
        if (!trainClass.Load())
        {
            trainClass.ID = Guid.NewGuid();
            tbClassID.Text = trainClass.ID.ToString();
            trainClass.CreateTime = DateTime.Now;
            trainClass.CreateUser = CurrentUser.DisplayName;
            trainClass.CreateUserID = CurrentUser.ID;
            Department dept = CurrentUser.GetMainDepartment();
            trainClass.FaceOrgan = dept.DisplayName;
            trainClass.FaceOrganID = CurrentUser.MainDepartmentID.ToString();
            if (OrganizationHelper.IsUserInRole(CurrentUser.ID, AppConfig.MinistryAdminRoleID))
            {
                trainClass.TrainType = "人事部";
                trainClass.Status = "待审核";
            }
            else if (OrganizationHelper.IsUserInRole(CurrentUser.ID, AppConfig.OrganizeAdminRoleID))
            {
                trainClass.TrainType = "区组织部";
                trainClass.Status = "终审通过";
            }
            else
            {
                trainClass.TrainType = "个人";
                trainClass.Status = "待审核";
            }
        }
        else
        {
            tbClassID.Text = ClassID.ToString();
        }
        try
        {
            trainClass.BeginTime = Convert.ToDateTime(tbBeginTime.Text);
        }
        catch (Exception)
        {
            trainClass.BeginTime = DateTime.MinValue;
        }
        try
        {
            trainClass.ApplyEndTime = Convert.ToDateTime(tbApplyEndTime.Text);
        }
        catch (Exception)
        {
            trainClass.ApplyEndTime = DateTime.MinValue;
        }
        try
        {
            trainClass.EndTime = Convert.ToDateTime(tbEndTime.Text);
        }
        catch (Exception)
        {
            trainClass.EndTime = DateTime.MinValue;
        }
        trainClass.ModifyTime = DateTime.Now;
        trainClass.State = "Live";
        trainClass.Comment = WebCommon.GetHTMLStyleStr(tbComment.Text);
        trainClass.ClassName = tbClassName.Text;
        trainClass.CourseInfo = tbCourseInfo.Text;
        trainClass.Curriculum = tbCurriculum.Text;
        trainClass.ApplyOrgan = tbDeptDisplayName.Text;
        trainClass.ApplyOrganID = tbDeptID.Text;
        trainClass.HostUnit = tbHostUnit.Text;
        float trainday = 0;
        float.TryParse(tbTrainDayCount.Text, out trainday);
        trainClass.TrainDayCount = trainday;
        trainClass.TrainLevel = ddlTrainLevel.SelectedValue == "请选择" ? string.Empty : ddlTrainLevel.SelectedValue;
        try
        {
            trainClass.Score = Convert.ToDouble(tbCourseScore.Text);
        }
        catch (Exception)
        {
            trainClass.Score = 0;
        }

        trainClass.Place = tbPlace.Text;
        trainClass.LectorInfo = tbLectorInfo.Text;

        //中心组学习课程
        if (tbClassName.Text.Contains("中心组学习"))
        {
            trainClass.FinishStatus = "初审结束";
        }
        trainClass.Save();

        //重新设置班次的ClassID
        //if (ClassID == Guid.Empty)
        //{
        //    string specialClassID = GetSpecialClassID(TempoClassID);
        //    DataTable dtOrder = BLTrain.GetOrderByClassID(new Guid(specialClassID));
        //    foreach (DataRow dr in dtOrder.Rows)
        //    {
        //        ClassOrder order = new ClassOrder();
        //        order.Init(dr);
        //        order.ClassID = trainClass.ID;
        //        order.Save();
        //    }
        //}

        ////删除今天之前的垃圾数据
        //BLTrain.DeleteNoUseOrder();

        string script = "<script>alert('保存成功!');refreshParent();window.close();</script>";
        //}
        //else
        //{
        //    script = "<script>alert('请增加培训时间!');</script>";

        //}
        ClientScript.RegisterStartupScript(this.GetType(), "Close", script);
    }

    protected void btnAddOrder_Click(object sender, EventArgs e)
    {
        string specialClassID = GetSpecialClassID(TempoClassID);
        ClassOrder order = new ClassOrder();
        order.ID = Guid.NewGuid();
        order.ClassID = ClassID == Guid.Empty ? new Guid(specialClassID) : ClassID;
        try
        {
            order.BeginTime = DateTime.Parse(tbOrderBeginTime.Text);
        }
        catch (Exception)
        {
        }
        try
        {
            order.EndTime = DateTime.Parse(tbOrderEndTime.Text);
        }
        catch (Exception)
        {
        }
        order.BeginHour = dlStartTime.Items[dlStartTime.SelectedIndex].Value;
        order.EndHour = dlEndTime.Items[dlEndTime.SelectedIndex].Value;
        order.Save();
        BindOrder();
    }

    protected void rptOrderInfo_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (e.CommandName == "Delete")
            {
                Guid orderID = new Guid(e.CommandArgument.ToString());
                BLTrain.DeleteOrder(orderID);
            }
        }
        BindOrder();
    }

    protected string GetSpecialClassID(string tempClassID)
    {
        //取双位月
        string month = DateTime.Now.Month < 10 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString();
        //取双位日
        string day = DateTime.Now.Day < 10 ? "0" + DateTime.Now.Day.ToString() : DateTime.Now.Day.ToString();
        //组合方式：前8位为1，中间8位为日期，最后16位为随机
        return "11111111-" + DateTime.Now.Year + "-" + month + day + tempClassID.Substring(tempClassID.Length - 18, 18);

    }
}
